package com.zhentao.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.common.constants.ArticleConstants;
import com.zhentao.file.service.impl.FileStorageServiceImpl;
import com.zhentao.mapper.ApArticleContentMapper;
import com.zhentao.mapper.ArticleMapper;
import com.zhentao.model.article.pojo.ApArticle;
import com.zhentao.model.article.pojo.ApArticleContent;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.userSearch.vo.SearchArticleVo;
import com.zhentao.service.ApArticleContentService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class ApArticleContentServiceImpl implements ApArticleContentService {

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageServiceImpl fileStorageService;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @SneakyThrows
    @Override
    @Async//开启异步处理
    public ResponseResult createStaticUrl(Long articleId) {
        //根据iD生成html静态文件，然后文件上传到minio里面
        //1.根据id获取文章内容
        ApArticleContent apArticleContent =
                apArticleContentMapper.selectOne(new QueryWrapper<ApArticleContent>().lambda().eq(ApArticleContent::getArticleId, articleId));
        if (apArticleContent != null) {
            //把内容通过freemarker生产html文件
            Template template = configuration.getTemplate("article.ftl");
            Map<String, Object> map = new HashMap<>();
            String content = apArticleContent.getContent();
            map.put("content", JSONArray.parseArray(content));

            StringWriter out = new StringWriter();
            template.process(map, out);
            //将html上传到minio里面
            InputStream inputStream = new ByteArrayInputStream(out.toString().getBytes(StandardCharsets.UTF_8));
            String url = fileStorageService.uploadHtmlFile(apArticleContent.getArticleId() + ".html", inputStream);

            //修改ap_article表里面的static_url字段
            ApArticle apArticle = new ApArticle();
            apArticle.setId(articleId);
            apArticle.setStaticUrl(url);
            articleMapper.updateById(apArticle);
            ApArticle a = articleMapper.selectById(articleId);
            //发送消息，创建索性
            createArticleESIndex(a, content, url);
            return ResponseResult.okResult(200, url);
        }
        return ResponseResult.errorResult(201, "文章不存在");

    }


    /**
     * 送消息，创建索引
     *
     * @param apArticle
     * @param content
     * @param url
     */
    private void createArticleESIndex(ApArticle apArticle, String content, String url) {
        SearchArticleVo vo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle, vo);
        vo.setContent(content);
        vo.setStaticUrl(url);

        kafkaTemplate.send(ArticleConstants.ARTICLE_ES_SYNC_TOPIC, JSON.toJSONString(vo));
    }

}
